<template>
  <!--菜谱管理/有效列表页面-->
  <div>
    <!--表单和搜索栏-->
    <div style="margin: 50px auto;width: fit-content">
      <el-input v-model="filter.name" type="text" placeholder="请输入搜索菜谱的名称" style="width: 800px;margin-right: 10px" @input="searchDebounce"/>
      <el-button type="primary" style="margin: 10px 5px" icon="el-icon-search" @click="search()">搜索</el-button>
      <el-button type="info" style="margin: 10px 5px" icon="el-icon-setting" @click="handleAdvancedSearch()">高级搜索
      </el-button>
      <el-button type="info" style="margin: 10px 5px" icon="el-icon-delete" @click="handleClear()">清除筛选</el-button>
      <el-button type="success" style="margin: 10px 5px" icon="el-icon-plus" @click="handleAdd()">添加菜谱</el-button>
      <!--四个不同的表单-->
      <el-dialog :title="title" :visible.sync="dialogFormVisible" center>
        <el-form :model="form">
          <el-form-item label="创建用户" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="模糊匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <!--            <el-input v-model="form.userId" autocomplete="off" style="width: 80%" />-->
            <el-select
              v-model="form.userId"
              filterable
              remote
              placeholder="请输入用户手机"
              :remote-method="searchUserByPhone"
              :loading="loading"
              :disabled="title==='编辑菜谱'"
              style="width: 80%"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="'用户名: '+item.username+'  手机号:'+item.phone"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="序号" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="精确匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <el-input v-model="form.id" autocomplete="off" :disabled="title!=='高级搜索'" style="width: 80%" />
          </el-form-item>
          <el-form-item label="名称" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="模糊匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <el-input v-model="form.name" autocomplete="off" style="width: 80%" />
          </el-form-item>
          <el-form-item label="种类" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="模糊匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <!--            <el-input v-model="form.userId" autocomplete="off" style="width: 80%" />-->
            <el-select
              v-model="form.type"
              placeholder="请选择种类"
              style="width: 80%"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="title==='添加菜谱'" label="关联食物" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="模糊匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <!--            <el-input v-model="form.userId" autocomplete="off" style="width: 80%" />-->
            <el-select
              v-model="relationship"
              multiple
              filterable
              remote
              placeholder="请输入食物名称"
              :remote-method="searchFoodByName"
              :loading="loading"
              style="width: 80%"
            >
              <el-option
                v-for="item in foodList"
                :key="item.createId"
                :label="'名称: '+item.name+'  别名：'+item.alias"
                :value="item.createId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="材料" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="模糊匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <el-input v-model="form.material" autocomplete="off" style="width: 80%" />
          </el-form-item>
          <el-form-item label="详情" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="模糊匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <el-input v-model="form.detail" autocomplete="off" style="width: 80%" />
          </el-form-item>
          <el-form-item v-show="title!=='高级搜索'" label="图片" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="this.$api.img.dishPic"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.pic" v-lazy="this.$api.img.server + form.pic" class="avatar">
              <i v-else id="avatar-uploader-icon" class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm()">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="编辑关系" :visible.sync="editRelationship" center>
        <el-form :model="form">
          <el-form-item label="关联食物" :label-width="formLabelWidth">
            <el-tooltip v-show="title==='高级搜索'" class="item" effect="dark" content="模糊匹配" placement="top-start">
              <i class="el-icon-question" style="margin-right: 20px" />
            </el-tooltip>
            <!--            <el-input v-model="form.userId" autocomplete="off" style="width: 80%" />-->
            <el-select
              v-model="relationship"
              multiple
              filterable
              remote
              placeholder="请输入食物名称"
              :remote-method="searchFoodByName"
              :loading="loading"
              style="width: 80%"
            >
              <el-option
                v-for="item in foodList"
                :key="item.createId"
                :label="'名称: '+item.name+'  别名：'+item.alias"
                :value="item.createId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editRelationship = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--显示的表格-->
    <el-table
      :data="rows"
      style="width: 100%"
      border
    >
      <el-table-column
        prop="id"
        label="序号"
        width="80"
        align="center"
      />
      <el-table-column
        prop="userId"
        label="创建用户"
        width="80"
        align="center"
      />
      <el-table-column
        prop="name"
        label="名称"
        width="200"
        align="center"
      />
      <el-table-column
        prop="type"
        label="种类"
        width="80"
        align="center"
        :formatter="formatterType"
      />
      <el-table-column
        prop="material"
        label="材料"
        width="300"
        align="center"
      />
      <el-table-column
        prop="detail"
        label="详情"
        width="450"
        align="center"
      />
      <el-table-column
        prop="likeCount"
        label="点赞量"
        width="80"
        align="center"
      />
      <el-table-column
        prop="commentCount"
        label="评论量"
        width="80"
        align="center"
      />
      <el-table-column
        label="操作"
        align="center"
      >
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="handleRelationship(row,$index)">编辑关联
          </el-button>
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="handleModify(row,$index)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleInvalid(row,$index)">失效</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器-->
    <el-pagination
      :current-page="index"
      :page-sizes="[3, 5, 10, 20]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;text-align: center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { debounce } from 'lodash'
export default {
  name: 'Apply',
  data() {
    return {
      relationship: [],
      editRelationship: false,
      foodList: [],
      options: [],
      list: [],
      loading: false,
      typeList: [],
      rows: [],
      filter: {
        id: '',
        name: '',
        material: '',
        detail: '',
        pic: '',
        type: '',
        userId: '',
        likeCount: '',
        comment_count: '',
        valid: ''
      },
      total: 100,
      size: 5,
      index: 1,
      title: '',
      dialogFormVisible: false,
      form: {
        id: '',
        name: '',
        material: '',
        detail: '',
        pic: '',
        type: '',
        userId: '',
        likeCount: '',
        comment_count: '',
        valid: ''
      },
      formLabelWidth: '120px'
    }
  },
  watch: {
    $route: {
      handler() {
        this.filter.id = this.$route.query.id
        this.search()
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.filter.id = this.$route.query.id
    this.init()
  },
  methods: {
    searchDebounce: debounce(function() {
      this.search()
    }, 300),
    searchUserByPhone(query) {
      if (query !== '') {
        this.loading = true
        var that = this
        setTimeout(() => {
          this.loading = false
          this.$api.user_active.search({ phone: query }, 0, 10).then(res => {
            that.options = res.data.rows
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    async handleInvalid(row, index) {
      const res = await this.$api.dish_manage.invalid({ id: row.id })
      this.$message.success(res.message)
      this.search()
    },
    searchFoodByName(query) {
      if (query !== '') {
        this.loading = true
        var that = this
        setTimeout(() => {
          this.loading = false
          this.$api.dish_manage.searchDefaultFood({ name: query }, 0, 10).then(res => {
            that.foodList = res.data.rows
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    handleClear() {
      this.filter = {
        id: '',
        name: '',
        material: '',
        detail: '',
        pic: '',
        type: '',
        userId: '',
        likeCount: '',
        comment_count: '',
        valid: ''
      }
      this.search()
    },
    handleAdvancedSearch() {
      this.title = '高级搜索'
      this.form = this.filter
      this.dialogFormVisible = true
    },
    handleAdd() {
      this.title = '添加菜谱'
      this.relationship = []
      this.foodList = []
      this.form = {
        id: '',
        name: '',
        material: '',
        detail: '',
        pic: '',
        type: '',
        userId: '',
        likeCount: '',
        comment_count: '',
        valid: ''
      }
      this.dialogFormVisible = true
      this.search()
    },
    async init() {
      const that = this
      await this.$api.dishType_active.search({}, 0, 999).then(res => {
        that.typeList = res.data.rows
      })
      this.search()
    },
    search() {
      const that = this
      this.$api.dish_manage.search(this.filter, this.index, this.size).then(response => {
        // console.log(response.data.rows)
        that.rows = response.data.rows
        // console.log(that.rows)
        // console.log(response.data.total)
        that.total = response.data.total
        // console.log(that.total)
      })
    },
    handleModify(row, index) {
      this.title = '编辑菜谱'
      this.dialogFormVisible = true
      this.form = row
    },
    handleRelationship(row, index) {
      this.title = '编辑关系'
      this.editRelationship = true
      const that = this
      this.relationship = []
      this.foodList = []
      this.$api.dish_manage.searchFoodByDishId(row.id).then(res => {
        that.foodList = res.data
        for (let i = 0; i < that.foodList.length; i++) {
          that.relationship[i] = that.foodList[i].createId
        }
      })
      this.form = row
    },
    handleSizeChange(val) {
      this.size = val
      this.search()
    },
    handleCurrentChange(val) {
      this.index = val
      this.search()
    },
    handleAvatarSuccess(res) {
      this.form.pic = res.data.address
    },
    beforeAvatarUpload(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async handleDialogConfirm() {
      switch (this.title) {
        case '编辑菜谱': {
          const edit = await this.$api.dish_manage.update({ id: this.form.id }, this.form)
          this.search()
          this.$message.success(edit.message)
          break
        }
        case '添加菜谱': {
          const ship = []
          for (let i = 0; i < this.relationship.length; i++) {
            ship[i] = { foodId: this.relationship[i] }
          }
          const add = await this.$api.dish_manage.add(this.form, ship)
          this.$message.success(add.message)
          this.search()
          break
        }
        case '高级搜索': {
          this.filter = this.form
          this.search()
          break
        }
        case '编辑关系': {
          const ship = []
          for (let i = 0; i < this.relationship.length; i++) {
            ship[i] = { foodId: this.relationship[i] }
          }
          const edit = await this.$api.dish_manage.updateRelationship({ id: this.form.id }, ship)
          this.$message.success(edit.message)
          break
        }
        default: {
          this.$message.error('系统故障！')
        }
      }
      this.dialogFormVisible = false
      this.editRelationship = false
    },
    formatterType(row, column) {
      for (let i = 0; i < this.typeList.length; i++) {
        if (row.type === this.typeList[i].id) {
          return this.typeList[i].name
        }
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
